<template>
  <div class="home-view">
    <div class="left">
      <div
        class="option"
        v-for="item in optionData"
        :key="item.id"
        :class="{ selected: item.id === selectedIndex }"
        @click="selectOption(item.id)"
      >
        <svg-icon :icon-file-name="item.icon"></svg-icon>
        <span>{{ item.text }}</span>
      </div>
    </div>
    <div class="content">
      <el-tabs v-model="activeName">
        <el-tab-pane label="推荐" name="first"
          ><post-view
            v-for="(item, index) in postData"
            :key="index"
            :postItem="item"
          ></post-view>
          <div v-if="loading" class="loading">加载中...</div></el-tab-pane
        >
        <el-tab-pane label="最新" name="second"
          ><post-view
            v-for="(item, index) in upToDatePostData"
            :key="index"
            :postItem="item"
          ></post-view>
          <div v-if="loading" class="loading">加载中...</div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="right">
      <div class="publish">
        <div class="text">
          <h1>发表文章</h1>
          <span>点亮在社区的每一天</span>
        </div>
        <el-button size="small" type="primary" @click="sendPost" plain>
          <svg-icon icon-file-name="text-add"></svg-icon>
          <span>发表文章</span>
        </el-button>
      </div>
      <div class="hot-posts">
        <div class="top">
          <div class="list-title">
            <div class="icon">
              <svg-icon icon-file-name="hot"></svg-icon>
            </div>
            <span>热点文章</span>
          </div>
          <div class="replace-it" @click="nextPage">
            <svg-icon icon-file-name="reload"></svg-icon>
            <span>换一换</span>
          </div>
        </div>
        <div class="list" v-for="(item, index) in paginatedPosts" :key="index">
          <div class="item" @click="lookPostClick(item)">
            <div
              :class="[
                'index',
                getColorClass(currentPage * postsPerPage + index),
              ]"
            >
              {{ item.index }}
            </div>
            <div class="title">
              <span>{{ item.title }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- <a class="admin-login" href="http://localhost:6061/">管理员登陆</a> -->
    </div>
    <!-- 备案信息 -->
    <div class="filings">
      <div class="security">
        <img
          src="../../assets/img/filings.png"
          alt="备案图标"
          draggable="false"
        />
        <a
          href="https://beian.mps.gov.cn/#/query/webSearch?code=34170202000700"
          rel="noreferrer"
          target="_blank"
          >皖公网安备34170202000700</a
        >
      </div>
      <span style="margin: 0 10px 0 10px">|</span>
      <div class="icp">
        <a href="https://beian.miit.gov.cn/" target="_blank"
          >皖ICP备2024055077号-1</a
        >
      </div>
    </div>
  </div>
</template>

<script>
import { addPostPageView } from "../../api/post";
import { mapState, mapMutations } from "vuex";
import { getToken, getUserId } from "../../utils/auth";
import PostView from "./components/PostView.vue";
import { EventBus } from "@/main";
import { getPostData, getPostHotData } from "../../api/post";
export default {
  components: {
    PostView,
  },
  data() {
    return {
      // 是否降序排序，即是否是最新
      isDescending: "0",
      // 判断是否有新的数据
      hasMore: true,
      // 文章数据
      postData: [],
      upToDatePostData: [],
      // 左侧选项栏
      selectedIndex: "0",
      optionData: [
        { id: "6", icon: "followed", text: "关注" },
        { id: "0", icon: "all-fill", text: "全部" },
        { id: "1", icon: "html5", text: "前端" },
        { id: "2", icon: "back-end", text: "后端" },
        { id: "3", icon: "AI", text: "人工智能" },
        { id: "4", icon: "read-fill", text: "阅读" },
      ],
      // 中间帖子部分
      loading: false,
      activeName: "first",
      PostCurrentPage: 1, // 文章的分页查询
      PostPageSize: 10, // 每页的查询条数
      // 文章榜单分页相关
      currentPage: 0,
      postsPerPage: 5,
      hotPosts: [],
    };
  },
  methods: {
    // 将当前访问的文章浏览量加一
    lookPostClick(item) {
      addPostPageView(item.postId).then((res) => {
        if (res.data.code === 1) {
          res;
        } else {
          this.$message.error("网络错误");
        }
      });
      // 跳转路由查看文章使用Vue Router获取目标路由的完整URL
      const routePath = this.$router.resolve({
        name: "LookPost",
        params: { postId: item.postId, postTitle: item.title },
      }).href;
      window.open(routePath, "_blank");
    },
    ...mapMutations({
      changeBottom: "scrollBar/changeBottom",
    }),
    // 滚动条到底部重新加载数据
    loadMore() {
      if (this.loading) return;
      this.getPostData();
      // 重新加载数据结束后，将滚动条是否置地变量置位false
      this.changeBottom();
    },
    // 分页条件查询获取文章数据
    getPostData() {
      if (!this.hasMore) {
        return;
      }
      this.loading = true;
      getPostData(
        getUserId(),
        this.selectedIndex,
        this.isDescending,
        this.PostCurrentPage,
        this.PostPageSize
      ).then((res) => {
        if (res.data.code === 1) {
          if (this.isDescending === "0") {
            // 推荐的数据
            this.postData = [...this.postData, ...res.data.data.rows];
            if (this.postData.length === res.data.data.total) {
              this.hasMore = false;
            }
          } else {
            // 最新的数据
            this.upToDatePostData = [
              ...this.upToDatePostData,
              ...res.data.data.rows,
            ];
            if (this.upToDatePostData.length === res.data.data.total) {
              this.hasMore = false;
            }
          }
          this.PostCurrentPage += 1;
        } else {
          this.$messages.error("网络错误");
        }
        this.loading = false;
      });
    },
    // 发表文章
    sendPost() {
      if (getToken() !== null) {
        this.$router.push({
          name: "publication",
          params: {
            postId: 0,
            postData: {},
          },
        });
      } else {
        // 发送全局事件，未登录
        EventBus.$emit("notLoggedIn");
      }
    },
    selectOption(index) {
      this.selectedIndex = index;
      this.PostCurrentPage = 1;
      this.postData = [];
      this.upToDatePostData = [];
      this.hasMore = true;
      this.getPostData();
      // console.log(this.selectedIndex);
    },
    // 分页展示文章榜单
    nextPage() {
      this.currentPage =
        (this.currentPage + 1) %
        Math.ceil(this.hotPosts.length / this.postsPerPage);
    },
    // 榜单颜色
    getColorClass(index) {
      if (index === 0) return "first-place";
      if (index === 1) return "second-place";
      if (index === 2) return "third-place";
      return "other-place";
    },
    // 获取榜单热点数据
    getPostHotData() {
      getPostHotData().then((res) => {
        if (res.data.code === 1) {
          let i = 1;
          const formattedData = res.data.data.map((item) => {
            return {
              index: i++,
              postId: item.postId,
              title: item.title,
            };
          });
          this.hotPosts = formattedData;
        } else {
          this.$messages.error("网络错误");
        }
      });
    },
  },
  computed: {
    paginatedPosts() {
      const start = this.currentPage * this.postsPerPage;
      const end = start + this.postsPerPage;
      return this.hotPosts.slice(start, end);
    },
    // vuex中滚动条状态变量
    ...mapState({
      isBottom: (state) => state.scrollBar.isBottom,
    }),
  },
  mounted() {
    this.getPostData();
    this.getPostHotData();
  },
  watch: {
    // 监听滚动条，当为true，也就是触底执行loadMore()
    isBottom(newVal) {
      if (newVal) {
        this.loadMore(); // 当 isBottom 变为 true 时触发获取数据的函数
      }
    },
    // 监听选中最新还是推荐
    activeName(newVal) {
      if (newVal === "second") {
        // console.log("选中了最新");
        this.isDescending = "1";
        this.hasMore = true;
      } else {
        // console.log("选中了推荐");
        this.isDescending = "0";
        this.hasMore = true;
      }
      this.PostCurrentPage = 1;
      this.postData = [];
      this.upToDatePostData = [];
      this.getPostData();
    },
  },
};
</script>

<style lang="less" scoped>
.home-view {
  overflow-y: auto;
  display: flex;
  width: 100%;
  justify-content: flex-start;
  gap: 26px;
  .left,
  .content {
    box-shadow: 0px 0px 2px #ccc;
    border-radius: 3px;
    background-color: #fff;
  }
  .left {
    // 绝对定位
    position: absolute;
    left: 6%;
    top: 80px;
    // height: 175px;
    width: 12%;
    padding: 8px;
    box-sizing: border-box;
    .option {
      border-radius: 3px;
      height: 40px;
      width: 100%;
      display: flex;
      align-items: center;
      cursor: pointer;
      &:hover {
        background-color: #f5f5f5;
      }
      &.selected {
        background-color: #eaf2ff;
        color: #1e80ff;
        svg {
          color: #1e80ff;
        }
        span {
          color: #1e80ff;
        }
      }
      svg {
        width: 20px;
        height: 20px;
        font-size: 18px;
        margin-left: 10px;
        color: #8a919f;
      }
      span {
        font-size: 14px;
        margin-left: 20px;
        color: #515767;
      }
    }
  }
  .content {
    padding: 7px 0;
    height: auto;
    width: 50%;
    margin-left: 20%;
    margin-top: 20px;
    .loading {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 10px;
      color: #ccc;
    }
  }
  .right {
    position: absolute;
    right: 11%;
    top: 80px;
    height: 60%;
    width: 18%;
    .publish,
    .hot-posts {
      width: 100%;
      background-color: #fff;
      border-radius: 3px;
      box-shadow: 0px 0px 2px #ccc;
    }
    .publish {
      height: 100px;
      padding: 10px 15px 0 15px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      overflow: hidden;
      .text {
        h1 {
          font-size: 18px;
          font-weight: bold;
        }
        span {
          font-size: 14px;
          color: #8a919f;
        }
      }
      .el-button {
        margin-top: 20px;
        width: 100px;
        height: 40px;
        svg {
          color: #1e80ff;
          margin-right: 2px;
        }
        span {
          margin-left: 5px;
          font-size: 14px;
        }
      }
    }
    .hot-posts {
      padding: 10px;
      box-sizing: border-box;
      margin-top: 30px;
      height: 255px;
      .top {
        padding: 0 15px 10px 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ccc;
        .list-title {
          display: flex;
          align-items: center;
          align-items: center;
          .icon {
            border-radius: 50%;
            background-color: #ff8259;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 25px;
            height: 25px;
            .svg-icon {
              color: #fff;
              font-size: 12px;
            }
          }
          span {
            margin-left: 5px;
          }
        }
        .replace-it {
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #8a919f;
          cursor: pointer;
          span {
            margin-left: 4px;
            // 禁止选中文本
            user-select: none;
          }
        }
        .replace-it:hover {
          color: #1e80ff;
        }
      }
      .list {
        display: flex;
        flex-direction: column;
        padding: 0 15px;
        .item {
          padding: 10px;
          box-sizing: border-box;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          &:hover {
            background-color: #f5f5f5;
            cursor: pointer;
          }
          .index {
            margin-right: 20px;
            font-weight: bold;
            &.first-place {
              background: linear-gradient(to bottom, #ff9966, #ff5e62);
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
              background-clip: text;
            }
            &.second-place {
              background: linear-gradient(to bottom, #ff7e5f, #feb47b);
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
              background-clip: text;
            }
            &.third-place {
              background: linear-gradient(to bottom, #f6d365, #fda085);
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
              background-clip: text;
            }
            &.other-place {
              color: gray;
            }
          }
          .title {
            font-size: 14px;
            color: #252933;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
  .filings {
    position: absolute;
    bottom: 2%;
    right: 6%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 12px;
    color: #8a919f;
    .security {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 7px;
      img {
        width: 15px;
        height: 15px;
        user-select: none;
      }
    }
    .icp {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    a {
      text-decoration: none;
      color: #8a919f;
      &:hover {
        color: #1e80ff;
      }
    }
  }
}
.admin-login {
  position: absolute;
  bottom: 10%;
  right: 70%;
  color: #8a919f;
  // 去除下划线
  text-decoration: none;
  &:hover {
    color: #1e80ff;
  }
}
</style>

<style scoped>
::v-deep .el-tabs__nav {
  margin-left: 35px !important;
}
::v-deep .el-tabs__header {
  margin: 0 !important;
}
.el-button--small {
  padding: 9px 6px !important;
}
.el-button--small:hover,
.el-button--primary.is-plain:focus,
.el-button--primary.is-plain:active {
  background-color: #e8f2ff;
  color: #409eff !important;
}
</style>